<template>
  <div class="app-container">
    <div>
      <el-row class="admin-top-g">
        <GButton
          :is-add-show="false"
          :is-edit-show="false"
          :is-del-show="false"
          :lists="options"
          :is-settings-show = "lookSetShow"
          @onAdd="addUser"
          @onEdit="editUser"
          @onDelete="delUser"
          @selectSettings="selectSettings"
      /></el-row>
      <br>

      <el-row class="common-row">
        <template v-if="limits.length >=1 && limits.filter(it => it.FName === '查看').length">
          <el-input v-model="keyword" clearable style="width: 160px;" placeholder="请输入名称" @keyup.native.enter="searchUser" @change="searchUser"/>
          <el-input v-model="fmodel" clearable style="width: 160px;" placeholder="请输入机型全称" @keyup.native.enter="searchUser" @change="searchUser"/>
          <!-- <el-select v-model="fstatus" clearable filterable style="width: 150px;" placeholder="请选择审核状态" @change="searchUser">
            <el-option
              v-for="item in statusList"
              :key="item.fstatus"
              :label="item.fname"
              :value="item.fstatus"/>
          </el-select> -->
          <el-select v-model="fbrand" clearable filterable style="width: 100px;" placeholder="请选择品牌" @change="searchUser">
            <el-option
              v-for="item in brandList"
              :key="item.finterid"
              :label="item.fname"
              :value="item.fname"/>
          </el-select>
          <el-button type="primary" icon="el-icon-search" @click="searchUser">搜索</el-button>
        </template>

        <el-upload
          v-if="limits.length >=1 && limits.filter(it => it.FName === '导入').length"
          ref="uploadBasic"
          :on-preview="handlePreviewBasic"
          :on-remove="handleRemoveBasic"
          :limit="1"
          :data="upDataBasic"
          :on-exceed="exceedBasic"
          :on-success = "noticeBasic"
          :file-list="fileListBasic"
          :before-upload="beforeAvatarUploadBasic"

          class="upload-demo"
          style="display: inline-block; margin-left: 0px;"
          action="/excel/zyImport"
        >
          <!-- <el-button size="small" type="primary" icon="el-icon-upload">导入</el-button> -->
        </el-upload>

        <el-button v-if="limits.length >=1 && limits.filter(it => it.FName === '导出').length" type="primary" icon="el-icon-my-export" @click="downData">导出</el-button>
        <!-- <el-button type="primary" icon="el-icon-my-updown" @click="handleDownload">下载{{ fmofanName }}模板</el-button> -->
        <!-- <el-button type="primary" icon="el-icon-my-updown" @click="handleDownload('加账WINGD技术部导入')">{{ fmofanName }}WINGD模板</el-button> -->
        <!-- <el-button type="primary" icon="el-icon-my-updown" @click="handleDownload('加账MAN技术部导入')">{{ fmofanName }}MAN模板</el-button> -->

        <!-- <el-button v-if="limits.length >=1 && limits.filter(it => it.FName === '审核').length" type="primary" icon="el-icon-circle-check" @click="check('1')">审核</el-button>
        <el-button v-if="limits.length >=1 && limits.filter(it => it.FName === '反审核').length" type="primary" icon="el-icon-close" @click="check('0')">反审</el-button> -->

        <!-- <el-button v-if="limits.length >=1 && limits.filter(it => it.FName === '新增').length" type="primary" icon="el-icon-circle-plus-outline" @click="AddQdf()">新增测试</el-button> -->

        <el-button type="primary" icon="el-icon-refresh" @click="refresh">刷新 </el-button>
        <el-button v-if="limits.length >=1 && limits.filter(it => it.FName === '基础设置查看').length" type="primary" @click="addBaseSettings">基础设置查看</el-button>
        <el-button v-if="limits.length >=1 && limits.filter(it => it.FName === '导入').length" type="primary" icon="el-icon-refresh" @click="exportTableData">导入 </el-button>

      </el-row>
    </div>
    <br>

    <el-dialog
      v-el-drag-dialog
      :visible.sync="brandModel"
      :close-on-click-modal="false"
      :show-close="true"
      title="加账成本(技术)详情"
      class="drag-set-modal"
      width="78%">
      <el-input
        v-model="jzKeyword"
        clearable
        size="mini"
        placeholder="搜索"
        style="width: 160px;float: left; margin-top: 10px; margin-right: 6px;z-index: 100000"
      />
      <vxe-grid
        id="toolbar_demo_1"
        ref="setTable"
        :print-config="{}"
        :import-config="{}"
        :export-config="{}"
        :form-config="formConfig"
        :columns="tableColumn"
        :toolbar-config="tableToolbar"
        :data="cgDataList"
        :custom-config="{storage: true}"
        :edit-config="{trigger: 'click', mode: 'row', showStatus: true}"
        :footer-method="jzcbFooterMethod"

        align="center"
        height="650"
        border
        show-overflow
        show-footer
        resizable
        keep-source
        @toolbar-button-click="toolbarButtonClickEvent"
        @cell-dblclick="cellDbclick"
        @toolbar-tool-click="toolbarToolClickEvent">
        <!-- <template #keyword_item="{ data }">
          <vxe-input v-model="data.keyword" type="text" placeholder="请输入名称"/>
        </template> -->
        <template #fbrand_edit="{ row }">
          <vxe-input v-model="row.fbrand"/>
        </template>
        <template #fcode_edit="{ row }">
          <vxe-input v-model="row.fcode"/>
        </template>
        <template #fname_edit="{ row }">
          <vxe-input v-model="row.fname"/>
        </template>
        <template #fprodno_edit="{ row }">
          <vxe-input v-model="row.fprodno"/>
        </template>
        <template #fallamount_edit="{ row }">
          <vxe-input v-model="row.fallamount"/>
        </template>
        <template #fstatus_edit="{ row }">
          <vxe-select v-model="row.fstatus" transfer>
            <vxe-option :value="1" label="已审"/>
            <vxe-option :value="0" label="未审"/>
          </vxe-select>
        </template>
      </vxe-grid>

    </el-dialog>
    <el-table
      v-loading="listLoading"
      v-if="limits.length >=1 && limits.filter(it => it.FName === '查看').length"
      ref="tableDataRef"
      :data="tableData"
      :header-cell-style="tableHeaderStyle"
      :summary-method="getSummaries"
      :height="tableHeight"
      class="tableCss table-summary"
      element-loading-text="正在加载"
      border
      show-summary
      highlight-current-row
      @header-click="headerClick"
      @selection-change="handleSelectionChange"
      @current-change="salaryCurrentChange">
      <!-- <el-table-column
        type="selection"
        width="55"/> -->
      <el-table-column
        v-for="(item, key) in formThead"
        :key="key"
        :prop="item"
        :label="item"
        align="center"
        show-overflow-tooltip>
        <template slot-scope="scope">{{ scope.row[item] }}</template>
      </el-table-column>
    </el-table>

    <!-- <el-pagination
      v-if="limits.length >=1 && limits.filter(it => it.FName === '查看').length"
      :total="total"
      :page-sizes="pagesizes"
      :page-size="pagesize"
      :current-page.sync="currentPage"
      class="jy-pagination"
      style="text-align: center; margin-top: 20px;"
      background
      layout="sizes, prev, pager, next, total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"/> -->

    <el-dialog v-el-drag-dialog :visible.sync="addUserModal" title="添加／编辑" width="30%">
      <hr style="height:1px;margin-top:-33px;border:none;border-top:1px solid #ddd;" >
      <el-form v-loading="loadingForm" ref="form" :rules="rules" :inline="true" :model="form" label-width="150px" class="form1">

        <el-row >
          <el-col v-for="item in dialogThead" :span="24" :key="item.fid ">

            <el-form-item :label="item.frepcap" :prop="item.frepfld" >
              <template v-if="item.frepmeg == 1">
                <template v-if="'fduijiebumen' === item.frepfld" >
                  <el-select v-model="form[item.frepfld]" class="select_el" clearable filterable placeholder="请选择" >
                    <el-option
                      v-for="item2 in duiyingBMList"
                      :key="item2.finterid"
                      :label="item2.fname"
                      :value="item2.fname"/>
                  </el-select>
                </template>

              </template>
              <!-- 多文本-->
              <template v-else-if="item.frepmeg == 6" >
                <template >
                  <el-input :rows="3" v-model="form[item.frepfld]" type="textarea" />
                </template>
              </template>
              <!-- 日期框-->
              <template v-else-if="item.frepmeg == 4" >
                <template >
                  <el-date-picker v-model="form[item.frepfld]" style="width:100%" class="date_el" type="date" placeholder="选择日期" value-format="yyyy-MM-dd" />
                </template>
              </template>
              <!-- 禁止编辑-->
              <template v-else-if="item.frepmeg == 5" >
                <template >
                  <el-input v-model="form[item.frepfld]" :disabled="editText"/>
                </template>
              </template>

              <!-- 输入框 -->
              <template v-else >
                <el-input v-model="form[item.frepfld]" />
              </template>
            </el-form-item>
          </el-col>
        </el-row>

        <div class="dialog-footer">
          <el-form-item >
            <el-button :loading="loadingForm" type="primary" @click="confirm" >确认</el-button>
            <el-button @click="addUserModal=false">取消</el-button>
          </el-form-item>
        </div>
      </el-form>
    </el-dialog>

    <el-dialog v-el-drag-dialog :visible.sync="fmodelModal" :close-on-click-modal="false" title="加账项目清单" class="config-dialog">
      <el-input v-model="fmodelKeyword" clearable placeholder="搜索" style="width: 160px;" @keyup.native.enter="searchFmodel" @change="searchFmodel" />
      <el-select v-model="fbrandCg" clearable placeholder="请选择品牌" @change="selectBrand">
        <el-option
          v-for="item in fbrandList"
          :key="item.value"
          :label="item.label"
          :value="item.value"/>
      </el-select>
      <el-select v-model="fdanweibumenCg" clearable placeholder="请选择部门" @change="selectBrand">
        <el-option
          v-for="item in fdanweibumenList"
          :key="item.value"
          :label="item.label"
          :value="item.value"/>
      </el-select>
      <el-button type="primary" @click="searchFmodel">搜索</el-button>
      <el-button type="primary" @click="fmodelConfirm">确认</el-button>
      <el-table
        v-loading="fmodelLoading"
        ref="cgTable"
        :data="fmodelListData"
        class="single-select-table"
        style="margin-top: 10px;"
        max-height="750"
        element-loading-text="正在加载"
        border
        highlight-current-row
        @selection-change="CgHandleSelectionChange">
        <el-table-column
          type="selection"
          width="55"/>
        <el-table-column
          align="center"
          prop="fcode"
          width="100"
          label="代码"/>
        <el-table-column
          align="center"
          prop="fname"
          width="200"
          label="名称"/>
        <el-table-column
          align="center"
          prop="ffaxamount"
          width="200"
          label="含税金额"/>
        <el-table-column
          align="center"
          prop="fzjqty"
          width="120"
          label="单位"/>
        <el-table-column
          align="center"
          prop="fdanweibumen"
          width="120"
          label="部门"/>
        <el-table-column
          align="center"
          prop="fqtyremark"
          width="160"
          label="数量注释"/>
        <el-table-column
          align="center"
          prop="fremark"
          label="备注"/>

      </el-table>
    </el-dialog>

    <!-- 参数配置 -->
    <el-dialog v-el-drag-dialog :visible.sync="configModal" :close-on-click-modal="false" class="config-dialog">
      <head-table
        :config-list="configList"
        :key-value="key"
        @updateConfigData="getUpdateConfigData" />
    </el-dialog>

    <!-- SQL弹窗 -->
    <el-dialog v-el-drag-dialog :visible.sync="dialogSQLModal" :append-to-body="true" title="执行结果">
      <el-form v-loading="loadingFormSQL" ref="formSQL" :rules="rulesSQL" :model="formSQL" label-width="120px">
        <el-form-item label="SQL语句" prop="gzsql">
          <el-input v-model="formSQL.gzsql" :autosize="{ minRows: 14 }" type="textarea" />
        </el-form-item>
        <el-form-item>
          <el-button :loading="loadingFormSQL" type="primary" @click="confirmSQL" >确认</el-button>
          <el-button @click="dialogSQLModal=false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 下载模板 -->
    <el-dialog :visible.sync="tableSetExcel" title="提示：信息导出" style="width:30%; margin:auto;">
      <el-button type="primary" @click="downloadFile1()">导出</el-button>
    </el-dialog>

    <el-dialog
      v-el-drag-dialog
      :visible.sync="baseSettings.fbaseModal"
      :close-on-click-modal="false"
      top="2vh"
      title="基础设置-加账技术成本"
      class="config-dialog jz-dialog">
      <div style="overflow:hidden; float: left; margin-top: 10px; margin-right: 6px;z-index: 10">
        <el-input
          v-model="baseSettings.fbaseKeyword"
          clearable
          style="width: 160px; float: left;z-index: 11"
          size="mini"
          placeholder="搜索"
          @keyup.native.enter="fbaseSearch"
          @change="fbaseSearch" />
        <el-select v-model="baseSettings.fbrand" size="mini" style="float: left;z-index: 11;" clearable placeholder="请选择品牌" @change="fbaseSearch">
          <el-option
            v-for="item in baseSettings.fbrandList"
            :key="item.value"
            :label="item.label"
            :value="item.value"/>
        </el-select>
        <el-select v-model="baseSettings.fjs" size="mini" style="float: left;z-index: 11;" clearable placeholder="请选择品牌" @change="fbaseSearch">
          <el-option
            v-for="item in baseSettings.fjsList"
            :key="item.value"
            :label="item.label"
            :value="item.value"/>
        </el-select>
        <!-- <el-select v-model="fdanweibumenCg" clearable placeholder="请选择部门" @change="selectBrand">
          <el-option
            v-for="item in fdanweibumenList"
            :key="item.value"
            :label="item.label"
            :value="item.value"/>
        </el-select> -->
      </div>
      <vxe-grid
        id="toolbar_demo_fbaseTable"
        ref="fbaseTable"
        :print-config="{}"
        :import-config="{}"
        :export-config="{}"
        :form-config="baseSettings.formConfig"
        :columns="baseSettings.fbaseTableColumn"
        :toolbar-config="baseSettings.tableToolbar"
        :data="baseSettings.fbaseData"
        :custom-config="{storage: true}"
        :edit-config="{trigger: 'click', mode: 'row', showStatus: true}"
        :height="calHeight"
        align="center"
        border
        resizable
        keep-source
        @edit-closed="editClosed"
        @toolbar-button-click="fbaseToolBarButtonClick"
        @toolbar-tool-click="fbaseToolbarToolClickEvent">
        <template #fbrand_edit="{ row }">
          <vxe-input v-model="row.fbrand"/>
        </template>
        <template #fcode_edit="{ row }">
          <vxe-input v-model="row.fcode"/>
        </template>
        <template #fname_edit="{ row }">
          <vxe-input v-model="row.fname"/>
        </template>
        <template #fprodno_edit="{ row }">
          <vxe-input v-model="row.fprodno"/>
        </template>
        <template #fallamount_edit="{ row }">
          <vxe-input v-model="row.fallamount"/>
        </template>
        <template #ffaxamount_edit="{ row }">
          <vxe-input v-model="row.ffaxamount"/>
        </template>
        <template #fqty_edit="{ row }">
          <vxe-input v-model="row.fqty"/>
        </template>
        <template #fzjqty_edit="{ row }">
          <vxe-input v-model="row.fzjqty"/>
        </template>
        <template #fdanweibumen_edit="{ row }">
          <vxe-select
            v-model="row.fdanweibumen"
            clearable
            multiple
            @change="dWbmChange">
            <vxe-option
              v-for="(item, i) in baseSettings.dwbmList"
              :key="i"
              :label="item"
              :value="item"
            />
          </vxe-select>
        </template>
        <template #fremark_edit="{ row }">
          <vxe-input v-model="row.fremark"/>
        </template>
        <template #fisgongshijs_edit="{ row }">

          <template
            v-if="row.fdanweibumen
              && row.fdanweibumen.length
            && row.fdanweibumen.includes('技术中心')">
            <vxe-select
              v-model="row.fisgongshijs"
              clearable
              @change="jsxzChange">
              <vxe-option
                v-for="(item, i) in baseSettings.fisgongshijsList"
                :key="i"
                :disabled="item.disabled"
                :label="item.label"
                :value="item.value"
              />
            </vxe-select>
          </template>
          <template v-else>
            <vxe-select
              v-model="row.fisgongshijs"
              clearable
              @change="jsxzChange">
              <vxe-option
                v-for="(item, i) in baseSettings.fisgongshijsList"
                :key="i"
                :label="item.label"
                :value="item.value"
                disabled
              />
            </vxe-select>
          </template>

        </template>
      </vxe-grid>
    </el-dialog>

    <!-- 导入 -->
    <el-dialog
      v-el-drag-dialog
      :title="importGrid.title"
      :visible.sync="importGrid.fmodal"
      :close-on-click-modal="false"
      :show-close="true"
      class="import-set-modal"
      width="78%"
      @close="closeImportDialog">
      <div class="search-grid" style="margin-bottom: 20px;">
        <!-- <vxe-button status="success" icon="vxe-icon-add" content="新增" @click="importGridAdd"/> -->
        <vxe-button status="success" icon="vxe-icon-save" content="保存" @click="importGridSave"/>
        <vxe-button class="import-excel" status="primary" content="导入Excel" @click="toImport" />
        <vxe-button status="success" icon="vxe-icon-delete" content="删除" @click="importGridDel"/>
        <ExcelImport
          :ref="importGrid.excelRefs"
          :data-row="importGrid.dataRow"
          :is-data-header="importGrid.isDataHeader"
          :value-match="importGrid.fieldArr"
          :accept="importGrid.accept"
          @changeExcel="uploadExamFile" />
      </div>
      <vxe-grid
        :class="importGrid.class"
        :id="importGrid.id"
        :ref="importGrid.gridRefs"
        :print-config="{}"
        :import-config="{}"
        :export-config="{}"
        :columns="importGrid.columns"
        :toolbar-config="importGrid.tableToolbar"
        :data="importGrid.data"
        :custom-config="{storage: true}"
        :edit-config="{trigger: 'click', mode: 'row', showStatus: true}"
        align="center"
        height="450"
        border
        resizable
        keep-source>
        <template v-for="item in importGrid.fieldCap" slot-scope="{row}" :slot="item.field+'_edit'">
          <vxe-input :key="item.field" v-model="row[item.field]" />
        </template>
      </vxe-grid>
    </el-dialog>

  </div>
</template>
<script>
let FRepKey = ''
let opername = ''
const defaultFormThead = []

import VXETable from 'vxe-table'
import 'vxe-table/lib/style.css'

import HeadTable from '../salary/headTable/index.vue'
import { configColumn, FSetbumen, checkStatus } from '../../api/salary'
import { download } from '../../mixins/download.js'
import { common } from '../../mixins/common'
import { brand } from '../../mixins/brand'
import { duiyingBM } from '../../mixins/duiyingBM'

import { pagination } from '../../mixins/pagination'
import { parseTime } from '../../utils/index'
import { tableConfig, apiSql, apiFileSave, getCBData } from '../../api/account'
import { FImportIJZ, genAdd, genDel, genList, FJZModel, FJZEdit, FJzDel, FJZSave } from '../../api/gen'
import { FJZset } from '../../api/peijian'
import '../../styles/common.scss'
import '../../styles/svg.scss'

import VXETablePluginShortcutKey from 'vxe-table-plugin-shortcut-key'
VXETable.use(VXETablePluginShortcutKey, {
  // 功能键设置
  setting: {
    'table.edit.tab.rightMove': 'Enter',
    'table.edit.tab.leftMove': 'shift + Tab'
  }
})

export default {
  name: 'Index',
  components: {
    HeadTable
  },
  filters: {
    parseTime(time, type) {
      return parseTime(time, type)
    }
  },
  mixins: [download, common, brand, duiyingBM, pagination],
  data() {
    return {
      importGrid: {
        class: 'import-set-modal',
        rows: '',
        fmodel: '',
        fbrand: '',
        title: '加账成本技术详情（导入）',
        excelRefs: 'importExcel', // ExcelImport
        dataRow: 0, // 数据开始行 默认从第0行开始
        isDataHeader: true,
        fieldCap: [
          // { field: 'fbrand', frecap: '品牌' },
          // { field: 'fcode', frecap: '代码' },
          // { field: 'fname', frecap: '名称' },
          // { field: 'fprodno', frecap: '型号' },
          // { field: 'fallamount', frecap: '金额' }
        ],
        fieldArr: [], // 数据列 必须与excel中的表列顺序相对应
        valueTitle: [], // frecap
        accept: '.xls,.xlsx',
        id: 'import-grid',
        gridRefs: 'importTable', // vxe-grid
        fmodal: false,
        data: [],
        columns: [
          { type: 'checkbox', width: 50 },
          { type: 'seq', width: 60 }
        ]
      },

      fdanweibumenCg: '2',
      fdanweibumenList: [
        { label: '采购部', value: '1' },
        { label: '技术中心', value: '2' },
        { label: '其他部门', value: '3' },
        { label: '全部', value: '0' }
      ],
      fmodelId: '',
      multipleSelection: [],
      fbrandCg: 'WINGD',
      fbrandList: [
        { label: 'WINGD', value: 'WINGD' },
        { label: 'MAN', value: 'MAN' }
      ],
      fmodelKeyword: '',
      fmodelLoading: false,
      fmodelModal: false,

      fmodelListData: [],
      fmodel: '',
      jzFmodel: '',
      jzKeyword: '',
      brandModel: false,
      cgDataList: [],
      tableToolbar: {
        size: 'small',
        buttons: [
          { code: 'search', status: 'primary', name: '搜索' },
          { code: 'myInsert', name: '新增' },
          { code: 'mySave', name: '保存', status: 'success' },
          { code: 'myDelete', name: '删除', status: 'primary' },
          { code: 'myFresh', name: '刷新', status: 'primary' },
          { code: 'myCheck', name: '审核', status: 'primary' },
          { code: 'myUnCheck', name: '反审核', status: 'primary' }
        ]
        // refresh: true
        // import: true,
        // export: true,
        // print: true,
        // zoom: true,
        // custom: true
      },
      formConfig: {
        data: {
          keyword: ''
        }
      },
      data: [],
      tableColumn: [
        { type: 'checkbox', width: 50 },
        { type: 'seq', width: 60 },
        { field: 'fbrand', title: '品牌', editRender: {}, slots: { edit: 'fbrand_edit' }},
        { field: 'fcode', title: '代码', editRender: {}, slots: { edit: 'fcode_edit' }},
        { field: 'fname', title: '名称', editRender: {}, slots: { edit: 'fname_edit' }},
        { field: 'fprodno', title: '型号', editRender: {}, slots: { edit: 'fprodno_edit' }},
        { field: 'fallamount', title: '金额', editRender: {}, slots: { edit: 'fallamount_edit' }},
        {
          field: 'fstatus', title: '审核状态',
          filters: [
            { value: 0, label: '未审' },
            { value: 1, label: '已审' }
          ],
          editRender: {
            name: '$select',
            options: [
              { value: 0, label: '未审' },
              { value: 1, label: '已审' }
            ]
          }, slots: { edit: 'fstatus_edit' }
        }
      ],

      fbrand: 'WINGD',
      fdanweibumen: 2,
      value: '',
      options: [],
      FRepKey: '',
      keyword: '',
      fdeleted: '',
      fdeletedList: [

      ],
      fdeletedListDiaL: [

      ],
      gapTime: '',
      start_time: '',
      end_time: '',

      // 表头、表格设置
      tableData: [],
      tableList: [],
      defaultFormThead: [],
      formThead: defaultFormThead,
      dialogThead: [],
      curData: {},

      listLoading: false,
      list: [],
      configModal: false,
      configLoading: false,

      loadingForm: false,
      configList: [],
      key: 0,
      // SQL弹窗
      dialogSQLModal: false,
      loadingFormSQL: false,
      formSQL: {
        gzsql: ''
      },
      rulesSQL: {

      },

      form: {},
      rules: {

      },
      addUserModal: false,
      // loadingForm: false

      fileList: [],

      // 批量删除
      checkData: [],
      selectedData: [],

      // 用户菜单
      menusList: [],
      limits: [],
      userKey: '',
      fmofanName: '',

      bmwzList: [ // 部门位置
        {
          finterid: 0,
          fname: '钢壳'
        },
        {
          finterid: 1,
          fname: '铝壳'
        },
        {
          finterid: 2,
          fname: '14500'
        }
      ],

      upData: {},
      fdeptname: '', // 部门
      bmList: [], // 部门
      xlList: [], // 学历
      zwList: [], // 职务
      xbList: [], // 性别
      lzztList: [],
      fileListBasic: [],
      baseList: [],
      upDataBasic: {},

      detail: '',
      opername: '',
      detailVisible: false,
      editText: false,
      tableSetExcel: false,
      lookSetShow: false,
      oriColumnData: [],

      // 基础设置
      baseSettings: {
        fbaseModal: false,
        fbaseKeyword: '',
        fbaseLoading: false,
        fbaseData: [],
        fbrand: 'WINGD',
        fbrandList: [
          { label: 'WINGD', value: 'WINGD' },
          { label: 'MAN', value: 'MAN' }
        ],
        // fjs   0 -全部 1- 技术
        fjs: '1',
        fjsList: [
          { label: '全部', value: '0' },
          { label: '技术中心', value: '1' }
        ],
        fdanweibumen: '1',
        fdanweibumenList: [
          { label: '采购部', value: '1' },
          { label: '技术中心', value: '2' },
          { label: '其他部门', value: '3' },
          { label: '全部', value: '0' }
        ],
        dwbmList: [],

        fisgongshijsList: [
          { label: '', value: '0', disabled: false },
          { label: '数量*金额*税率/生效台数', value: '1', disabled: false },
          { label: '数量*金额*税率', value: '2', disabled: false },
          { label: '工时*装试车间单价*1.13', value: '3', disabled: false },
          { label: '数量*柴油参数值*税率', value: '4', disabled: false },
          { label: '数量*燃气参数值*税率', value: '5', disabled: false },
          { label: '不做计算', value: '6', disabled: false }
        ],
        fbaseTableColumn: [
          { type: 'checkbox', width: 50 },
          // { type: 'seq', width: 60 },
          { field: 'fbrand', title: '品牌', editRender: {}, slots: { edit: 'fbrand_edit' }},
          { field: 'fcode', title: '代码', editRender: {}, slots: { edit: 'fcode_edit' }},
          { field: 'fname', title: '名称', editRender: {}, slots: { edit: 'fname_edit' }},
          { field: 'ffaxamount', title: '含税金额', editRender: {}, slots: { edit: 'ffaxamount_edit' }},
          { field: 'fqty', title: '数量', editRender: {}, slots: { edit: 'fqty_edit' }},
          { field: 'fzjqty', title: '单位', editRender: {}, slots: { edit: 'fzjqty_edit' }},
          // { field: 'fdanweibumen', title: '部门', editRender: {}, slots: { edit: 'fdanweibumen_edit' }},
          { field: 'fdanweibumen', title: '部门',
            width: 350,
            editRender: {
              name: 'select',
              events: { change: this.dWbmChange },
              options: [
                { label: '采购部', value: '采购部' },
                { label: '技术中心', value: '技术中心' },
                { label: '售后服务部', value: '售后服务部' },
                { label: '生产管理部', value: '生产管理部' }
              ]
            }, slots: { edit: 'fdanweibumen_edit' }
          },
          { field: 'fremark', title: '备注', editRender: {}, slots: { edit: 'fremark_edit' }},
          { field: 'fisgongshijs', title: '技术公式选择',
            width: 350,
            editRender: {
              name: '$select',
              events: { change: this.jsxzChange },
              options: []
            }, slots: { edit: 'fisgongshijs_edit' }
          }
        ],
        formConfig: {
          data: {
            keyword: ''
          }
        },
        tableToolbar: {
          size: 'small',
          buttons: [
            { code: 'search', status: 'primary', name: '搜索' },
            { code: 'myInsert', visible: true, name: '新增', status: 'success' },
            { code: 'mySave', visible: true, name: '保存', status: 'success' },
            { code: 'myExport', visible: true, name: '导出', status: 'primary' },
            { code: 'myFresh', name: '刷新', status: 'primary' },
            { code: 'myDelete', name: '删除', status: 'primary' }
          ]
        // refresh: true
        // import: true,
        // export: true,
        // print: true,
        // zoom: true,
        // custom: true
        }
      }

    }
  },
  async mounted() {
    // await this.getColumns()
    await this.getBmList()

    this.calHeight = (Number(this.tableHeight))
    console.log(this.calHeight, ' this.calHeight')
    // console.log(this.tableHeight * , ' this.tableHeight * 80%')

    this.userKey = this.$route.meta.FRepKey
    FRepKey = this.$route.meta.FRepKey
    this.upDataBasic.db = this.globalDb.db
    this.opername = decodeURIComponent(this.globalDb.fname)
    opername = decodeURIComponent(this.globalDb.fname)

    this.upDataBasic.FRepKey = this.$route.meta.FRepKey
    this.lookSetShow = JSON.parse(localStorage.getItem('flookSet'))

    this.upData.db = this.globalDb.db
    this.fmofanName = this.$route.meta.title

    // await this.getAllData()
    await this.getCBDataList()
    // await this.getFJZModelData()
    // await this.getGenListData()
    // await this.getFJZsetData()

    // 菜单列表（权限）
    const menuRes = JSON.parse(localStorage.getItem('setMenuData'))
    this.menusList = menuRes
    if (menuRes.length >= 1) {
      menuRes.map(it => {
        it.children.map(item => {
          if (item.fobjectid === this.userKey) {
            this.$set(this, 'limits', item.child)
          }
        })
      })
    }

    // console.log(this.limits, ' this.limits')

    // const buttons = this.baseSettings.tableToolbar.buttons
    // this.$set(buttons[1], 'visible', !!(this.limits.length >= 1 && this.limits.filter(it => it.FName === '基础设置新增').length))
    // this.$set(buttons[2], 'visible', !!(this.limits.length >= 1 && this.limits.filter(it => it.FName === '基础设置保存').length))
    // this.$set(buttons[3], 'visible', !!(this.limits.length >= 1 && this.limits.filter(it => it.FName === '基础设置导出').length))
    // this.$set(buttons[5], 'visible', !!(this.limits.length >= 1 && this.limits.filter(it => it.FName === '基础设置删除').length))
    // this.$set(this.baseSettings.tableToolbar, 'buttons', buttons)
  },
  methods: {
    async getBmList() {
      try {
        const res = await FSetbumen({
          db: this.globalDb.db,
          opername: this.opername
        })
        // console.log(res, ' res')
        if (res.Error === 0) {
          this.baseSettings.dwbmList = res.Data
        }
      } catch (err) {
        console.log(err)
      }
    },
    dWbmChange(val) {
      console.log(val, ' val111 ')
      console.log(val.value, ' val')
      setTimeout(() => {
        const $fbaseTable = this.$refs.fbaseTable
        const fisgongshijisCol = $fbaseTable.getColumnByField('fisgongshijs')
        const jsList = val.value
        const fisgongshijsList = [
          { label: '', value: '', disabled: false },
          { label: '数量*金额*税率/生效台数', value: '1', disabled: false },
          { label: '数量*金额*税率', value: '2', disabled: false },
          { label: '工时*装试车间单价*1.13', value: '3', disabled: false },
          { label: '数量*柴油参数值*税率', value: '4', disabled: false },
          { label: '数量*燃气参数值*税率', value: '5', disabled: false },
          { label: '不做计算', value: '6', disabled: false }
        ]
        if (jsList.includes('技术中心')) {
          this.$set(fisgongshijisCol, 'editRender.options', fisgongshijsList)
          // fisgongshijisCol.editRender.options = fisgongshijsList
        } else {
          fisgongshijisCol.editRender.options = this.baseSettings.fisgongshijsList
        }
        console.log(fisgongshijisCol.editRender.options, ' fisgongshijisCol.editRender.options')
      }, 0)
    },
    editClosed({ row }) {
      console.log(row, ' editClosed')
      if (row.fdanweibumen && !row.fdanweibumen.includes('技术中心')) {
        this.$set(row, 'fisgongshijs', '')
      }
    },
    jsxzChange(val) {
      console.log(val, ' val  jsxzChange')
    },
    getColumns() {
      this.importGrid.fieldCap.map(item => {
        this.importGrid.fieldArr.push(item.field)
        this.importGrid.valueTitle.push(item.frecap)
        this.importGrid.columns.push({
          field: item.field,
          title: item.frecap,
          editRender: {},
          slots: { edit: item.field + '_edit' }
        })
      })
    },
    exportTableData() {
      this.importGrid.fmodal = true
      this.importGridDel()
    },
    // 获取数据
    async uploadExamFile(data) {
      console.log('导出的数据', data)
      // console.log(this.importGrid.isDataHeader, ' this.importGrid.isDataHeader')
      if (this.importGrid.isDataHeader) {
        this.$set(this.importGrid, 'fieldCap', [])
        this.$set(this.importGrid, 'fieldArr', [])
        this.$set(this.importGrid, 'valueTitle', [])
        this.$set(this.importGrid, 'columns', [
          { type: 'checkbox', width: 50 },
          { type: 'seq', width: 60 }])
        // console.log(1)
        // console.log(data.snKeys, ' data.snKeys')
        if (data.snKeys && data.snKeys.length) {
          data.snKeys.map(it => {
            // console.log(it, ' it')
            this.importGrid.fieldCap.push({
              field: it,
              frecap: it
            })
          })
          await this.getColumns()
        }
        this.importGrid.data = data.retn
        // console.log(this.importGrid.data, ' this.importGrid.data')
      } else {
        this.importGrid.data = data
      }
      // console.log(this.importGrid.fieldCap, ' this.importGrid.fieldCap')
    },
    importData() {
      this.importGrid.fmodal = true
      this.importGridDel()
    },
    toImport() {
      this.$refs[this.importGrid.excelRefs].open()
    },
    importGridAdd() { // 新增
      const $grid = this.$refs[this.importGrid.gridRefs]
      $grid.insertAt(-1, -1)
    },
    importGridDel() { // 删除当前行
      const $grid = this.$refs[this.importGrid.gridRefs]
      if ($grid) {
        const checkData = $grid.getCheckboxRecords()
        if (checkData.length) {
          $grid.removeCheckboxRow()
        } else {
          if (this.importGrid.isDataHeader) {
            this.$set(this.importGrid, 'fieldCap', [])
            this.$set(this.importGrid, 'fieldArr', [])
            this.$set(this.importGrid, 'valueTitle', [])
            this.$set(this.importGrid, 'columns', [
              { type: 'checkbox', width: 50 },
              { type: 'seq', width: 60 }])
            // this.importGrid.fieldCap.length = 0
            // this.importGrid.fieldArr.length = 0
            // this.importGrid.valueTitle.length = 0
            // this.importGrid.columns.length = 0
          }
          this.importGrid.data = []
          $grid.remove($grid.getCheckboxRecords())
        }
      }
    },
    async importGridSave() { // 保存
      const $grid = this.$refs[this.importGrid.gridRefs]
      $grid.getRecordset()
      const { fullData } = $grid.getTableData()
      // console.log(tableData, ' importGridSave tableData')
      try {
        // const res = await FImportJZDetail({
        const res = await FImportIJZ({
          FRepKey,
          // fbillno: this.importGrid.fbillno,
          // rows: this.importGrid.rows,
          opername: this.opername,
          // fmodel: this.importGrid.fmodel,
          // fbrand: this.importGrid.fbrand,
          data: fullData
        })
        if (res.Error === 0) {
          this.$message({
            message: res.Message,
            type: 'success'
          })
          this.importGrid.rows = ''
          this.importGrid.fbillno = ''
          this.importGrid.fmodel = ''
          this.importGrid.fbrand = ''
          this.importGridDel()
          this.importGrid.fmodal = false
          await this.getCBDataList()
          // console.log(this.importGrid, ' this.importGrid')
        } else {
          this.$message({
            message: res.Message,
            type: 'error'
          })
        }
      } catch (error) {
        console.log(error)
      }
    },
    closeImportDialog() {
      this.importGrid.rows = ''
      this.importGrid.fbillno = ''
      this.importGrid.fmodel = ''
      this.importGrid.fbrand = ''
      this.importGridDel()
    },
    // 导入数据上面----------------
    fbaseHandleSelectionChange(val) {
      if (val.length) {
        this.multipleSelection = val
      } else {
        this.multipleSelection = []
      }
      if (val.length > 1) {
        this.$refs.fbaseTable.clearSelection()
        this.$refs.fbaseTable.toggleRowSelection(val.pop())
      }
    },
    async fbaseSearch() {
      await this.getFJZsetData()
    },
    async fbaseEdit() {
      await this.getFJZsetData()
    },
    fbaseAdd() {
    },
    async fbaseDel() {
      return
      // eslint-disable-next-line no-unreachable
      if (this.multipleSelection.length < 1) {
        this.$message({
          message: '请选中要删除的一行',
          type: 'warning'
        })
        return
      }
      const fid = this.multipleSelection[0].fid
      // console.log(fid, ' fid')
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        cancelButtonClass: 'btn-custom-cancel',
        type: 'warning'
      }).then(async() => {
        const res = await genDel({
          db: this.globalDb.db,
          opername,
          data: this.selectedData,
          fid,
          FRepKey
        })
        if (res.Error === 0) {
          this.$message({
            message: res.Message,
            type: 'success'
          })
          await this.getAllData()
          return
        }
        this.$message({
          message: res.Message,
          type: 'error'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    async addBaseSettings() {
      this.baseSettings.fbaseModal = true
      await this.getFJZsetData()
    },
    async getFJZsetData() {
      try {
        this.baseSettings.fbaseLoading = true
        const res = await FJZset({
          FRepKey,
          opername,
          fbrand: this.baseSettings.fbrand,
          fjs: this.baseSettings.fjs,
          fdanweibumen: '2',
          keyword: this.baseSettings.fbaseKeyword
        })
        // console.log(res, ' res')
        if (res.Error === 0) {
          if (res.Data.length) {
            res.Data.map(item => {
              // item.fdanweibumen = item.fdanweibumen.split(',')
              // item.fisgongshijs = Number(item.fisgongshijs) > 0 ? Number(item.fisgongshijs) : 0
              // this.jsxzChange(item.fisgongshijs)
            })
            console.log(res.Data, 'res.Data')
            this.baseSettings.fbaseData = res.Data
            this.baseSettings.fbaseLoading = false
            setTimeout(() => {
              const $fbaseTable = this.$refs.fbaseTable
              if ($fbaseTable) {
                const fisgongshijisCol = $fbaseTable.getColumnByField('fisgongshijs')
                fisgongshijisCol.editRender.options = this.baseSettings.fisgongshijsList
              }
            }, 0)
          }
        }
      } catch (error) {
        this.baseSettings.fbaseLoading = false
        console.log(error)
      }
    },
    async fbaseToolBarButtonClick({ code }) {
      const $grid = this.$refs.fbaseTable
      const getCheckboxRecordsData = $grid.getCheckboxRecords()
      const { insertRecords, removeRecords, updateRecords } = $grid.getRecordset()
      const { tableData } = $grid.getTableData()
      switch (code) {
        case 'search':
          this.getFJZsetData()
          break
        case 'myInsert':
          $grid.insertAt(-1, -1)
          break
        case 'mySave':
          if (insertRecords.length === 0 && updateRecords.length === 0 && removeRecords.length === 0) {
            VXETable.modal.message({ content: `新增 ${insertRecords.length} 条，更新 ${updateRecords.length} 条`, status: 'warning', zIndex: 99999 })
            return
          }
          if (tableData.length) {
            tableData.map(item => {
              // if (Array.isArray(item.fdanweibumen)) {
              //   item.fdanweibumen = item.fdanweibumen.join(',')
              // }
              // if (!item.fisgongshijs) {
              //   item.fisgongshijs = ''
              // }
              // console.log(item.fdanweibumen, ' item.fdanweibumen')
            })
          }

          if (updateRecords.length) {
            console.log(updateRecords, ' updateRecords')
            const isJsTData = updateRecords.filter(item => item.fdanweibumen.includes('技术中心'))
            // const isHasVal = isJsTData.every(item => Number(item.fisgongshijs) > 0)
            const isHasVal = isJsTData.every(item => Number(item.fisgongshijs) > 0)
            const notJsData = isJsTData.filter(item => Number(item.fisgongshijs) <= 0)
            if (!isHasVal) {
              for (let i = 0; i < notJsData.length; i++) {
                VXETable.modal.message({ content: `当前行代码${notJsData[i].fcode}，部门为${notJsData[i].fdanweibumen.join(',')}，请选择技术公式`, status: 'warning', zIndex: 9999 })
                break
              }
              return
            }
            // const isHasVal = isJsTData.every(item => {
            //   console.log(item, ' item')
            // })
            // console.log(isJsTData, ' isJsTData')
            console.log(isHasVal, ' isHasVal')
            // if (!isHasVal) {
            //   VXETable.modal.message({ content: `请选择技术公式`, status: 'warning', zIndex: 9999 })
            //   return
            // }
          }

          if (insertRecords.length) {
            console.log(insertRecords, ' insertRecords')
            const isJsInTData = insertRecords.filter(item => item.fdanweibumen.includes('技术中心'))
            const isHasInVal = isJsInTData.every(item => Number(item.fisgongshijs) > 0)
            const notJsData = isJsInTData.filter(item => Number(item.fisgongshijs) <= 0)
            // console.log(isJsTData, ' isJsTData')
            // console.log(isHasInVal, ' isHasInVal')
            if (!isHasInVal) {
              for (let i = 0; i < notJsData.length; i++) {
                VXETable.modal.message({ content: `新增当前行，部门为${notJsData[i].fdanweibumen.join(',')}，请选择技术公式`, status: 'warning', zIndex: 9999 })
                break
              }
              return
            }
          }
          try {
            const res = await FJZSave({
              fbrand: this.baseSettings.fbrand,
              FRepKey,
              opername: this.opername,
              insertRecords,
              updateRecords,
              removeRecords,
              data: tableData
            })
            if (res.Error === 0) {
              this.$message({
                message: res.Message,
                type: 'success'
              })
              this.brandModel = false
              await this.getFJZsetData()
              this.$nextTick(() => {
                this.$refs.tableDataRef.doLayout()
              })
            } else {
              this.$message({
                message: res.Message,
                type: 'error'
              })
            }
          } catch (error) {
            console.log(error)
          }
          break
        // eslint-disable-next-line no-case-declarations
        case 'myDelete':
          if (getCheckboxRecordsData.length === 0) {
            VXETable.modal.message({ content: `请选中一行`, status: 'warning', zIndex: 9999 })
            return
          }

          const fids = getCheckboxRecordsData.map(it => it.fid)

          // console.log(getCheckboxRecordsData, ' getCheckboxRecordsData')
          // console.log(fids, ' fids')
          const isExisFid = fids.every(fid => Number(fid) >= 0)
          if (!isExisFid) {
            const row = getCheckboxRecordsData.filter(it => !it.fid)
            // console.log(row, ' row')
            setTimeout(async() => {
              $grid.remove(row)
            })
            return
          }
          // return
          try {
            const res = await FJzDel({
              db: this.globalDb.db,
              opername: this.opername,
              data: getCheckboxRecordsData,
              fid: fids.join(','),
              FRepKey
            })
            if (res.Error === 0) {
              this.$message({
                message: res.Message,
                type: 'success'
              })
              // this.brandModel = false
              setTimeout(async() => {
                $grid.removeCheckboxRow()
              })
              await this.getFJZsetData()
            } else {
              this.$message({
                message: res.Message,
                type: 'error'
              })
            }
          } catch (error) {
            console.log(error)
          }

          break
        // eslint-disable-next-line no-case-declarations
        case 'myExport':
          this.header = []
          this.headerKeys = []
          // this.listData = []
          this.appendName = '基础设置' + this.baseSettings.fbrand
          this.baseSettings.fbaseTableColumn.slice(1).map((item, idx) => {
            for (const i in item) {
              if (i === 'field') {
                this.headerKeys[idx] = item.field
              }
              if (i === 'title') {
                this.header[idx] = item.title
              }
            }
          })
          this.listData = []
          if (!getCheckboxRecordsData.length) {
            if (this.baseSettings.fbaseData.length) {
              this.baseSettings.fbaseData.map((item, idx) => {
                this.listData[idx] = {}
                for (const i in item) {
                  if (this.headerKeys.includes(i)) {
                    this.listData[idx][i] = item[i]
                  }
                }
              })
            }
          } else {
            this.listData = getCheckboxRecordsData
          }
          this.listData.map(item => {
            this.baseSettings.fisgongshijsList.map(it => {
              console.log(it.label, ' it')
              if (Number(item.fisgongshijs) === Number(it.value)) {
                item.fisgongshijs = it.label
              }
            })
          })
          this.exportData()
          break
        case 'myFresh':
          this.getFJZsetData()
          break
      }
    },
    fbaseToolbarToolClickEvent({ code }) {
      const $grid = this.$refs.fbaseTable
      switch (code) {
        case 'myPrint':
          $grid.print()
          break
      }
    },
    CgHandleSelectionChange(val) {
      // console.log(val, ' CgHandleSelectionChange ', this.fmodel)
      if (val.length) {
        this.multipleSelection = val
      } else {
        this.multipleSelection = []
      }
      if (val.length > 1) {
        this.$refs.cgTable.clearSelection()
        this.$refs.cgTable.toggleRowSelection(val.pop())
      }
    },
    async cellDbclick({ row, rowIndex, $rowIndex, column, columnIndex, $columnIndex, $event }) {
      console.log(row, ' row')
      if (column.field === 'fcode') {
        this.fmodelId = row._X_ROW_KEY
        this.fmodelModal = true
        await this.getGenListData()
      }
    },
    async searchFmodel() {
      await this.getGenListData()
    },
    async selectBrand() {
      await this.getGenListData()
    },
    fmodelConfirm() {
      const $grid = this.$refs.setTable
      const { tableData } = $grid.getTableData()
      tableData.map(it => {
        if (it._X_ROW_KEY === this.fmodelId) {
          this.$set(it, 'fcode', this.multipleSelection[0].fcode)
          this.$set(it, 'fbrand', this.multipleSelection[0].fbrand)
          this.$set(it, 'fallamount', this.multipleSelection[0].ffaxamount)
          this.$set(it, 'fname', this.multipleSelection[0].fname)
          this.$set(it, 'fprodno', this.fmodel)
        }
      })
      this.fmodelModal = false
    },
    async getGenListData() {
      try {
        this.listLoading = true
        const res = await FJZset({
          db: this.globalDb.db,
          opername: this.opername,
          keyword: this.fmodelKeyword,
          fbrand: this.fbrandCg,
          fdanweibumen: this.fdanweibumenCg,
          limit: 200,
          page: 1,
          FRepKey
        })
        this.listLoading = false

        this.fmodelListData = res.Data
      } catch (error) {
        // this.listLoading = false
      }
    },
    sumNumFooter(list, field) {
      let count = 0
      list.forEach(item => {
        count += Number(item[field])
      })
      return count
    },
    jzcbFooterMethod({ columns, data }) {
      const sums = []
      columns.forEach((column, columnIndex) => {
        if (columnIndex === 0) {
          sums.push('合计')
        } else {
          if (column.property === 'fallamount') {
            const sumTemp = this.sumNumFooter(data, column.property)
            // console.log(sumTemp, ' sumTemp')
            sums.push(sumTemp.toFixed(2))
          } else {
            sums.push(' ')
          }
        }
      })
      // 返回一个二维数组的表尾合计
      return [sums]
    },
    async toolbarButtonClickEvent({ code }) {
      const $grid = this.$refs.setTable
      const getCheckboxRecordsData = $grid.getCheckboxRecords()
      const { insertRecords, removeRecords, updateRecords } = $grid.getRecordset()
      const { tableData } = $grid.getTableData()
      switch (code) {
        case 'search':
          this.getFJZModelData()
          break
        case 'myInsert':
          $grid.insertAt(-1, -1)
          break
        case 'mySave':

          if (insertRecords.length === 0 && updateRecords.length === 0 && removeRecords.length === 0) {
            VXETable.modal.message({ content: `新增 ${insertRecords.length} 条，更新 ${updateRecords.length} 条`, status: 'warning', zIndex: 99999 })
            return
          }

          try {
            const res = await FJZEdit({
              FRepKey,
              opername: this.opername,
              insertRecords,
              updateRecords,
              removeRecords,
              data: tableData
            })
            if (res.Error === 0) {
              this.$message({
                message: res.Message,
                type: 'success'
              })
              this.brandModel = false
              await this.getCBDataList()
            } else {
              this.$message({
                message: res.Message,
                type: 'error'
              })
            }
          } catch (error) {
            console.log(error)
          }

          break
        case 'myDelete':
          if ($grid.getCheckboxRecords().length === 0) {
            VXETable.modal.message({ content: `请选中一行`, status: 'warning' })
            return
          }
          setTimeout(async() => {
            // const { removeRecords } = $grid.getRecordset()
            $grid.removeCheckboxRow()
            // try {
            //   const res = await FJZEdit({
            //     FRepKey,
            //     opername: this.opername,
            //     insertRecords,
            //     updateRecords,
            //     removeRecords,
            //     tableData
            //   // formdata: this.formData
            //   })
            //   if (res.Error === 0) {
            //     this.$message({
            //       message: res.Message,
            //       type: 'success'
            //     })
            //   }
            // } catch (error) {
            //   console.log(error)
            // }
          })
          break
        case 'myFresh':
          this.getFJZModelData()
          break
        case 'myCheck': // 审核
          this.checkDetail(1, getCheckboxRecordsData)
          break
        case 'myUnCheck': // 反审核
          this.checkDetail(0, getCheckboxRecordsData)
          break
      }
    },
    // 1—审核，0—反审
    async checkDetail(Fstatus, checkData) {
      console.log(checkData, ' checkData')
      if (!checkData.length) {
        this.$message({
          message: '请选择表格行数据',
          type: 'error'
        })
        return
      }
      const fids = checkData.map(it => it.fid)
      // console.log(fids, ' fids')
      if (Number(Fstatus) === 1) {
        try {
          const res = await checkStatus({
            db: this.globalDb.db,
            opername: decodeURIComponent(this.globalDb.fname),
            loginname: decodeURIComponent(this.globalDb.fname),
            FRepKey,
            Fstatus, // 1—审核，0—反审
            fid: fids.join(',')

          })
          if (res.Error === 0) {
            this.$message({
              message: res.Message,
              type: 'success'
            })
            await this.getFJZModelData()
          } else {
            this.loadingForm = false
            this.$message({
              message: res.Message,
              type: 'error'
            })
          }
        } catch (error) {
          console.log(error)
        }
      } else {
        try {
          const res = await checkStatus({
            db: this.globalDb.db,
            opername: decodeURIComponent(this.globalDb.fname),
            loginname: decodeURIComponent(this.globalDb.fname),
            FRepKey,
            Fstatus, // 1—审核，0—反审
            fid: fids.join(','),
            appname: ''
          })
          if (res.Error === 0) {
            this.$message({
              message: res.Message,
              type: 'success'
            })
            await this.getFJZModelData()
          } else {
            this.loadingForm = false
            this.$message({
              message: res.Message,
              type: 'error'
            })
          }
        } catch (error) {
          console.log(error)
        }
      }
    },
    toolbarToolClickEvent({ code }) {
      const $grid = this.$refs.xGrid
      switch (code) {
        case 'myPrint':
          $grid.print()
          break
      }
    },
    async getCBDataList() {
      try {
        this.configLoading = true
        const res = await getCBData({
          db: this.globalDb.db,
          opername,
          fbrand: this.fbrand,
          keyword: this.keyword,
          fmodel: this.fmodel,
          fdanweibumen: this.fdanweibumen,
          FRepKey: FRepKey
        })
        if (res.Error === 0) {
          if (res.Data.length) {
            this.formThead = Object.keys(res.Data[0])
          } else {
            this.formThead = []
          }
          setTimeout(() => {
            this.tableData = res.Data
          }, 0)
          // console.log(this.formThead, ' this.formThead')
          this.header = JSON.parse(JSON.stringify(this.formThead))
          this.headerKeys = JSON.parse(JSON.stringify(this.formThead))
          this.listData = JSON.parse(JSON.stringify(res.Data))
        }
        // this.key = FRepKey
        this.configLoading = false
      } catch (error) {
        this.configLoading = false
      }
    },
    // 刷新
    refresh() {
      window.location.reload()
    },

    async toDetail(data) {
      this.detailVisible = true
      this.detail = data
    },

    selectFBirthday(val) {
      this.form.fbirthday = parseTime(val, '{y}-{m}-{d}')
    },
    selectFHireDate(val) {
      this.form.fhiredate = parseTime(val, '{y}-{m}-{d}')
    },
    selectFLeaveDate(val) {
      this.form.fleavedate = parseTime(val, '{y}-{m}-{d}')
    },
    // -----------------上传开始---------------------
    beforeAvatarUpload(file) {
      var testmsg = file.name.substring(file.name.lastIndexOf('.') + 1)
      const extension = testmsg === 'xls' || testmsg === 'xlsx'
      const isLt2M = file.size / 1024 / 1024 < 1
      if (!extension) {
        this.$message({
          message: '上传文件只能是 xls/xlsx格式!',
          type: 'warning'
        })
      }
      if (!isLt2M) {
        this.$message({
          message: '上传文件大小不能超过 1MB!',
          type: 'warning'
        })
      }

      const fd = new FormData()
      fd.append('file', file)

      if (extension) {
        return true
      } else {
        this.$message.warning('只能上传excel文件格式xls/xlsx')
        return false
      }
    },

    async submitUpload() {
      this.$refs.upload.submit()
    },

    handleRemove(file, fileList) {

    },
    handlePreview(file) {

    },
    exceed() {
      // 重复选择文件,弹出错误弹窗
      this.$message('最多仅支持上传一个文件')
    },
    notice(e) {
      if (e.code === 200) {
        this.$message(e.message)
      } else {
        this.$message(e.message)
      }
    },
    // -----------------上传结束---------------------
    // 导出数据
    async downData() {
      // await this.getAllBodyData()
      // await this.getAllHeadData()
      this.appendName = this.fbrand
      await this.exportData()
    },
    async getAllData() {
      await this.getBodyData()
      await this.getHeadData()
    },

    selectSettings(val) {
      if (val === 0) {
        this.settings()
      } else if (val === 1) {
        this.dialogSQL()
      }
    },
    settings() {
      this.configModal = true
      this.getTableConfig()
    },

    // 更新数据
    async getUpdateConfigData() {
      await this.getTableConfig()
      await this.getBodyData()
      await this.getHeadData()
    },

    // SQL修改/更新
    async dialogSQL() {
      this.dialogSQLModal = true
      try {
        const res = await apiSql({
          db: this.globalDb.db,
          opername,
          FRepKey
        })

        if (res.Error === 0) {
          this.formSQL.gzsql = res.Data
          this.formSQL.FRepKey = FRepKey
        }
        setTimeout(() => {
          this.$refs['formSQL'].clearValidate()
        })
      } catch (error) {
        // console.log(error)
      }
    },

    confirmSQL() {
      this.$refs['formSQL'].validate(async(valid) => {
        if (valid) {
          try {
            this.formSQL.db = this.globalDb.db
            this.formSQL.opername = opername
            const res = await apiFileSave(this.formSQL)
            if (res.Error === 0) {
              this.dialogSQLModal = false
              this.$message({
                message: res.Message,
                type: 'success'
              })
            } else {
              this.$message({
                message: res.Message,
                type: 'error'
              })
            }
          } catch (error) {
            // console.log(error)
          }
        } else {
          return false
        }
      })
    },

    // 设置字段
    async getTableConfig() {
      try {
        this.configLoading = true
        const res = await tableConfig({
          db: this.globalDb.db,
          opername,
          key: FRepKey
        })
        this.configList = res.Data
        this.key = FRepKey
        this.configLoading = false
      } catch (error) {
        this.configLoading = false
      }
    },

    // 表头数据
    async getHeadData() {
      try {
        this.listLoading = true
        this.header = []
        this.headerKeys = []
        this.listData = []
        const res = await configColumn({
          db: this.globalDb.db,
          opername,
          FRepKey
        })
        this.listLoading = false
        this.formThead = res.Data
        this.oriColumnData = res.Data

        // this.tableList = []
        this.formThead.map(item => {
          this.tableList.map(it => {
            if (item.freptype === 131) {
              it[item.frepfld] = Number(it[item.frepfld]).toFixed(item.fdecplaces)
            }
          })
        })
        this.tableData = this.tableList.slice()

        // 获取显示表头键值对
        this.formThead.filter(item => {
          if (!item.frephide) {
            this.header.push(item.frepcap)
            this.headerKeys.push(item.frepfld)
          }
        })
        // 获取显示表体数据
        const listData = this.tableList.slice()
        listData.map((item, index) => {
          this.listData[index] = {}
          this.headerKeys.map(it => {
            this.listData[index][it] = item[it]
          })
        })

        // 去除内码
        const arr = res.Data.slice()
        arr.map((item, index) => {
          if (item.frepfld === 'fid') {
            arr.splice(index, 1)
          }
        })

        this.dialogThead = arr.filter(item => item.funcontrol !== 1)
      } catch (error) {
        this.listLoading = false
      }
    },

    // 表体数据————erp职员列表
    async getBodyData() {
      try {
        this.listLoading = true
        const res = await genList({
          db: this.globalDb.db,
          opername,
          keyword: this.keyword,
          fstatus: this.fstatus,

          limit: this.pagesize,
          page: this.currentPage,
          FRepKey
        })
        this.listLoading = false

        this.tableList = res.Data
        this.total = res.total
      } catch (error) {
        this.listLoading = false
      }
    },
    async getFJZModelData() {
      try {
        // this.listLoading = true
        const res = await FJZModel({
          db: this.globalDb.db,
          opername: decodeURIComponent(this.globalDb.fname),
          // opername,
          keyword: this.jzKeyword,
          fmodel: this.jzFmodel,
          fdanweibumen: '2',
          FRepKey
        })
        console.log(res, ' res')
        // this.listLoading = false
        this.cgDataList = res.Data
        // this.total = res.total
      } catch (error) {
        // this.listLoading = false
      }
    },
    async searchUser() {
      // await this.getAllData()
      await this.getCBDataList()
      this.$nextTick(() => {
        this.$refs.tableDataRef.doLayout()
      })
    },
    async handleSizeChange(val) {
      this.currentPage = 1
      this.pagesize = val
      await this.getAllData()
    },
    async handleCurrentChange(val) {
      this.currentPage = val
      await this.getAllData()
    },
    salaryCurrentChange(val) {
      this.curData = val
    },

    // 下载
    async handleDownload(excelName) {
      const url = window.location.href.split('/dist')[0]
      window.open(`${url}/uploads/${excelName}.xlsx`)
      // const res = await downFileUrl({
      //   db: this.globalDb.db,
      //   opername,
      //   FRepKey
      // })
      // if (res.Error === 0) {
      //   this.tableSetExcel = true
      //   this.url = res.Data
      // } else {
      //   this.$message({
      //     message: res.Message,
      //     type: 'error'
      //   })
      // }
    },

    downloadFile1() {
      this.tableSetExcel = false
      window.open('/api/downloadFile?FRepKey=' + FRepKey)
    },

    // -----------------上传模板开始---------------------
    beforeAvatarUploadBasic(file) {
      var testmsg = file.name.substring(file.name.lastIndexOf('.') + 1)
      const extension = testmsg === 'xls' || testmsg === 'xlsx'
      const isLt2M = file.size / 1024 / 1024 < 1
      if (!extension) {
        this.$message({
          message: '上传文件只能是 xls/xlsx格式!',
          type: 'warning'
        })
      }
      if (!isLt2M) {
        this.$message({
          message: '上传文件大小不能超过 1MB!',
          type: 'warning'
        })
      }

      const fd = new FormData()
      fd.append('file', file)

      if (extension) {
        return true
      } else {
        this.$message.warning('只能上传excel文件格式xls/xlsx')
        return false
      }
    },

    async submitUploadBasic() {
      this.$refs.uploadBasic.submit()
    },

    handleRemoveBasic(file, fileList) {

    },
    handlePreviewBasic(file) {

    },
    exceedBasic() {
      // 重复选择文件,弹出错误弹窗
      this.$message('最多仅支持上传一个文件')
    },

    noticeBasic(e) {
      if (e.Error === 0) {
        this.$message(e.Message)
        this.getAllData()
        this.$refs.uploadBasic.clearFiles()
      } else {
        this.$message(e.Message)
      }
    },

    // 添加
    async addUser() {
      this.editText = false
      this.form = {}
      const data = {}
      this.dialogThead.map(item => { data[item.frepfld] = '' })
      for (const i in data) {
        this.$set(this.form, i, data[i])
      }
      setTimeout(() => {
        this.$refs['form'].clearValidate()
      })

      this.addUserModal = true
    },

    // 修改
    async editUser() {
      const data = this.selectedData[0]

      if (data && Number(data.fstatus) === 1) {
        this.$message({
          message: '已审核，不能修改！',
          type: 'error'
        })
        return
      }

      this.editText = true
      this.form = {}
      if (this.selectedData.length !== 1) {
        this.$message({
          message: '请选中要编辑的一行',
          type: 'warning'
        })
        return
      }

      this.dialogThead.map(item => { this.$set(this.form, item.frepfld, '') })
      this.form.fid = 0
      this.addUserModal = true
      for (const i in this.form) {
        this.form[i] = data[i]
        this.dialogThead.map(item => {
          if (item.frepmeg === 1 && i === item.frepfld && !data[i]) {
            this.form[i] = ''
          }
        })
      }
      setTimeout(() => {
        this.$refs['form'].clearValidate()
      })
    },

    async confirm() {
      this.$refs['form'].validate(async(valid) => {
        if (valid) {
          this.loadingForm = true
          try {
            this.form.db = this.globalDb.db
            this.form.opername = opername
            this.form.FRepKey = FRepKey

            const res = await genAdd(this.form)
            if (res.Error === 0) {
              this.loadingForm = false
              this.addUserModal = false
              this.$message({
                message: res.Message,
                type: 'success'
              })

              await this.getAllData()
            } else {
              this.loadingForm = false

              this.$message({
                message: res.Message,
                type: 'error'
              })
            }
          } catch (error) {
            this.loadingForm = false
          }
        } else {
          return false
        }
      })
    },

    async delUser() {
      const data = this.checkData
      if (data.length < 1) {
        this.$message({
          message: '请选中要删除的一行',
          type: 'warning'
        })
        return
      }
      const dataTemp = this.selectedData
      const isFstatus = dataTemp.filter(it => Number(it.fstatus) === 1)

      if (isFstatus.length) {
        this.$message({
          message: '已审核，不能删除！',
          type: 'error'
        })
        return
      }

      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        cancelButtonClass: 'btn-custom-cancel',
        type: 'warning'
      }).then(async() => {
        const fid = data.join(',')
        const res = await genDel({
          db: this.globalDb.db,
          opername,
          data: this.selectedData,
          fid: fid,
          FRepKey

        })
        if (res.Error === 0) {
          this.$message({
            message: res.Message,
            type: 'success'
          })
          await this.getAllData()
          return
        }
        this.$message({
          message: res.Message,
          type: 'error'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 合计
    getSummaries({ columns, data }) {
      const sums = []
      columns.forEach((column, columnIndex) => {
        if (columnIndex === 0) {
          sums[columnIndex] = '合计'
        } else {
          // if (arr.indexOf(column.property) >= 0) {
          //   sums[columnIndex] = this.sumNum(data, column.property).toFixed(2)
          // } else {
          //   sums[columnIndex] = ''
          // }
          const values = data.map(item => Number(item[column.property]))
          if (!values.every(value => isNaN(value))) {
            sums[columnIndex] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return ((prev + curr) * 100) / 100
              } else {
                return (prev * 100) / 100
              }
            }, 0)
            // sums[columnIndex] += ' '
            sums[columnIndex] = sums[columnIndex].toFixed(2)
          } else {
            sums[columnIndex] = ''
          }
        }
      })
      // 返回一个二维数组的表尾合计
      const sum2 = Number(sums[sums.length - 1]).toFixed(2)
      sums[sums.length - 1] = sum2
      return sums
    },

    sumNum(list, field) { // DONE
      let count = 0
      list.forEach(item => {
        count += Number(item[field]) * 100
      })
      return (count / 100)
    },

    // 1—审核，0—反审
    async check(Fstatus) {
      if (!this.checkData.length) {
        this.$message({
          message: '请选择表格行数据',
          type: 'error'
        })
        return
      }
      if (Number(Fstatus) === 1) {
        this.$confirm('是否审核, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          cancelButtonClass: 'btn-custom-cancel',
          type: 'warning'
        }).then(async() => {
          try {
            const res = await checkStatus({
              db: this.globalDb.db,
              opername: decodeURIComponent(this.globalDb.fname),
              loginname: decodeURIComponent(this.globalDb.fname),
              FRepKey,
              Fstatus, // 1—审核，0—反审
              fid: this.checkData.join(',')

            })
            if (res.Error === 0) {
              this.$message({
                message: res.Message,
                type: 'success'
              })
              await this.getAllData()
            } else {
              this.loadingForm = false
              this.$message({
                message: res.Message,
                type: 'error'
              })
            }
          } catch (error) {
            console.log(error)
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
      } else {
        try {
          const res = await checkStatus({
            db: this.globalDb.db,
            opername: decodeURIComponent(this.globalDb.fname),
            loginname: decodeURIComponent(this.globalDb.fname),
            FRepKey,
            Fstatus, // 1—审核，0—反审
            fid: this.checkData.join(','),
            appname: ''
          })
          if (res.Error === 0) {
            this.$message({
              message: res.Message,
              type: 'success'
            })
            await this.getAllData()
          } else {
            this.loadingForm = false
            this.$message({
              message: res.Message,
              type: 'error'
            })
          }
        } catch (error) {
          console.log(error)
        }
      }
    },
    async headerClick(column) {
      this.brandModel = true
      this.jzKeyword = ''
      this.jzFmodel = column.label
      await this.getFJZModelData()
    },
    handleSelectionChange(val) {
      this.checkData = []
      this.selectedData = val
      val.map(it => {
        this.checkData.push(it.fid)
      })
    }

  }
}

</script>
<style lang="scss" scoped>
.config-dialog ::v-deep .el-dialog {
  width: 90%;
}
.config-dialog ::v-deep .single-select-table thead .el-table-column--selection .cell {
  display: none;
}
.config-dialog, .drag-set-modal ::v-deep .el-dialog__body {
  padding: 0 20px;
 }
 .drag-set-modal {
  ::v-deep .vxe-table--render-default .vxe-body--column.col--ellipsis,
  ::v-deep .vxe-table--render-default.vxe-editable .vxe-body--column
  {
      height: 16px!important;
  }
}
.import-set-modal ::v-deep .el-dialog__body {
  padding: 0 20px;
}
.jz-dialog ::v-deep .el-dialog__body {
  padding: 0 20px;
}
.jz-dialog ::v-deep .vxe-table--body-wrapper {
  padding-bottom: 200px!important;
}
</style>
